<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="结算状态">
        <el-select style="width: 110px;" placeholder="结算状态" clearable v-model="dataForm.status" @change="onChange">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in settlementStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="收货单位">
        <el-select filterable style="width: 100%" v-model="dataForm.companyId" placeholder="收货单位" @change="onChange">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in receiveCompanyList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          :editable="false"
          type="month"
          v-model="dataForm.billDate"
          value-format="yyyy-MM"
          format="yyyy-MM"
          style="width:150px;"
          placeholder="选择账期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <!--        <el-button v-if="isAuth('tms:settlementrecord:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>-->
        <el-button v-if="isAuth('tms:settlementrecord:export')" type="primary" @click="downloadFile()">导出</el-button>
        <!--        <el-button v-if="isAuth('tms:settlementrecord:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>-->
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        fixed
        width="200px"
        prop="companyName"
        header-align="center"
        align="center"
        label="收货单位">
      </el-table-column>
      <el-table-column
        prop="billDate"
        header-align="center"
        align="center"
        label="账期">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="结算状态">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? '未结算' : '已结算' }}
        </template>
      </el-table-column>
      <el-table-column
        width="140px"
        prop="weight"
        header-align="center"
        align="center"
        label="总运输吨数">
      </el-table-column>
      <el-table-column
        width="120px"
        prop="shipmentAmount"
        header-align="center"
        align="center"
        label="总运费(元)">
      </el-table-column>
      <el-table-column
        width="140px"
        prop="shipmentCount"
        header-align="center"
        align="center"
        label="总运输次数">
      </el-table-column>

      <el-table-column
        width="150px"
        prop="ticketDate"
        header-align="center"
        align="center"
        label="出票日期">
      </el-table-column>
      <el-table-column
        prop="ticketMaker"
        header-align="center"
        align="center"
        label="出票人">
      </el-table-column>
      <el-table-column
        prop="ticketCollector"
        header-align="center"
        align="center"
        label="收票人">
      </el-table-column>

      <el-table-column
        width="170px"
        prop="settlementTime"
        header-align="center"
        align="center"
        label="结算时间">
      </el-table-column>
      <el-table-column
        width="300px"
        prop="note"
        header-align="center"
        align="center"
        label="备注">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" v-if="isAuth('tms:settlementrecord:settle') && scope.row.status==0 && !isCurrentMonth(scope.row.billDate)" size="small"
                     @click="addOrUpdateHandle(scope.row.id,scope.row.companyId)">结算
          </el-button>
          <el-button type="text" size="small" @click="detailHandle(scope.row.id)">明细</el-button>
<!--          <el-button type="text" v-if="isAuth('tms:settlementrecord:export')" size="small"-->
<!--                     @click="exportHandle(scope.row.id,scope.row.companyName)">导出明细-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <settlement v-if="addOrUpdateVisible" :receiveCompanyList="receiveCompanyList" ref="addOrUpdate"
                @refreshDataList="getDataList"></settlement>
    <settlementDetail v-if="detailVisible" ref="detail"></settlementDetail>
  </div>
</template>

<script>
import AddOrUpdate from './settlementrecord-add-or-update'
import settlementDetail from './settlementDetail'
import settlement from './settlement'
//import {getCurrentMonth, download} from '@/utils/utils'
import Utils from '@/utils/utils'
export default {
  data () {
    return {
      detailVisible: false,
      receiveCompanyList: [],
      settlementStatusList: [{label: '已结算', value: 1}, {label: '未结算', value: 0}],
      dataForm: {
        companyId: '',
        billDate: '',
        status: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate, settlement, settlementDetail
  },
  activated () {
    this.dataForm.billDate = Utils.getCurrentMonth()
    this.getDataList()
    this.getReceiveCompanyList()
  },
  methods: {
    onChange(){
      this.pageIndex =1;
      this.getDataList();
    },
    isCurrentMonth (str) {
      const date = new Date(str)
      const now = new Date()
      const dateYear = date.getFullYear()
      const dateMonth = date.getMonth()
      const nowYear = now.getFullYear()
      const nowMonth = now.getMonth()

      return dateYear === nowYear && dateMonth === nowMonth
    },
    exportHandle (id, name) {
      this.$http({
        url: this.$http.adornUrl('/tms/settlementrecord/exportDetail'),
        method: 'get',
        responseType: 'blob', //application/octet-stream
        params: this.$http.adornParams({
          'id': id,
        })
      }).then(({data}) => {
        console.log(data.size)
        if (data.size > 0) {

          Utils.download(data, this.dataForm.billDate + name + '账单明细')
        }

      })
    },
    detailHandle (id) {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.detail.init(id,this.dataForm.billDate)
      })
    },
    getReceiveCompanyList () {
      this.$http({
        url: this.$http.adornUrl('/tms/company/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 999
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.receiveCompanyList = data.page.list

        }
      })
    },
    downloadFile () {

      this.$http({
        url: this.$http.adornUrl('/tms/settlementrecord/export'),
        method: 'get',
        responseType: 'blob', //application/octet-stream
        params: this.$http.adornParams({
          'companyId': this.dataForm.companyId,
          'billDate': this.dataForm.billDate,
          'status': this.dataForm.status
        })
      }).then(({data}) => {
        console.log(data.size)
        if (data.size > 0) {

          download(data, this.dataForm.billDate + '账单')
        }

      })
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/tms/settlementrecord/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'companyId': this.dataForm.companyId,
          'billDate': this.dataForm.billDate,
          'status': this.dataForm.status
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id, companyId) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, companyId)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/tms/settlementrecord/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
  }
}
</script>
